/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arg.deploy.webapp.user.ctrl;

import com.arg.deploy.bean.User;
import com.arg.deploy.common.security.SecurityMD5;
import com.arg.deploy.core.hibernate.UserCore;
import com.arg.deploy.webapp.common.AlertMessages;
import com.arg.deploy.webapp.common.MainPageController;
import com.arg.deploy.webapp.common.ResourceUtil;
import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Textbox;

/**
 *
 * @author sorasaks
 */
public class UserCtrl extends MainPageController {
    
    private static final Logger LOG = Logger.getLogger(UserCtrl.class);
    private Textbox txtUsername;
    private Textbox txtPassword;
    private Button btnSignin;
    
    public UserCtrl() {
        super("default.message.title.authentification", Boolean.TRUE, Boolean.TRUE);
    }
    
    @Override
    public void doAfterCompose(Component comp) throws Exception {
        super.doAfterCompose(comp); //To change body of generated methods, choose Tools | Templates.
        initialEventListener();
    }
    
    private void initialEventListener() {
        txtUsername.addEventListener(Events.ON_OK, new Signin());
        txtPassword.addEventListener(Events.ON_OK, new Signin());
        btnSignin.addEventListener(Events.ON_CLICK, new Signin());
    }
    
    private class Signin implements EventListener {
        
        @Override
        public void onEvent(Event t) throws Exception {
            SecurityMD5 md5 = new SecurityMD5(txtPassword.getValue());
            User user = UserCore.getUserSignin(txtUsername.getValue(), md5.encoding());
            
            LOG.info(":::::::::::::::::::: user = " + user);
            if (user == null) {
                AlertMessages.alertMessage(ResourceUtil.getLabel("default.alert.message.invalid.signin", locale));
            } else {
                if (user.getUsername().equals("admin")) {
                    Executions.getCurrent().getSession().setAttribute(USER_PERMISSION, user);
                    Executions.getCurrent().sendRedirect(ADMIN_URL);
                } else {
                    Executions.getCurrent().getSession().setAttribute(USER_PERMISSION, user);
                    Executions.getCurrent().sendRedirect(USER_URL);
                }
            }
        }
    }
}
